Perl substr()用法及代码示例 |
您所在的位置:网站首页 › perl 字符串替换 › Perl substr()用法及代码示例 |
Perl中的substr()从传递给函数的字符串中返回一个子字符串,从给定索引开始直至指定长度。如果未指定长度,则此函数默认情况下从给定索引开始返回字符串的其余部分。如果要将字符串的该部分替换为其他子字符串,也可以将替换字符串传递给substr()函数。该索引和长度值也可能为负,这会改变字符串中索引计数的方向。例如,如果传递了一个负索引,则子字符串将从字符串的右端返回,而如果我们传递负数长度,则该函数将从字符串的后端保留那么多字符。 用法: substr(string, index, length, replacement) 参数: string:从中提取子字符串的字符串 index:子字符串的起始索引 length:子串的长度 replacement: 替换子字符串(如果有)返回值:所需长度的子字符串 注意:可以省略参数“长度”和“替换”。 例子1 #!/usr/bin/perl # String to be passed $string = "GeeksForGeeks"; # Calling substr() to find string # without passing length $sub_string1 = substr($string, 4); # Printing the substring print "Substring 1 : $sub_string1\n"; # Calling substr() to find the # substring of a fixed length $sub_string2 = substr($string, 4, 5); # Printing the substring print "Substring 2 : $sub_string2 ";输出: Substring 1 : sForGeeks Substring 2 : sForG例子2 #!/usr/bin/perl # String to be passed $string = "GeeksForGeeks"; # Calling substr() to find string # by passing negative index $sub_string1 = substr($string, -4); # Printing the substring print "Substring 1 : $sub_string1\n"; # Calling substr() to find the # substring by passing negative length $sub_string2 = substr($string, 4, -2); # Printing the substring print "Substring 2 : $sub_string2 ";输出: Substring 1 : eeks Substring 2 : sForGee
|
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |